//
//  ButtonViewController.swift
//  DemoProject
//
//  Created by hao on 2018/7/18.
//  Copyright © 2018年 hao. All rights reserved.
//

import UIKit

class ButtonViewController: BaseTableViewController {

    let disposeBag = DisposeBag()
    
    lazy var button1: UIButton = {
        let _btn = UIButton(type: .system)
        _btn.tag = 1
        self.tableHeadView.addSubview(_btn)
        _btn.snp.makeConstraints({ make in
            make.left.equalTo(20)
            make.centerY.equalTo(self.tableHeadView)
        })
        _btn.setTitle("测试按钮1", for: .normal)
        return _btn
    }()
    
    lazy var button2: UIButton = {
        let _btn = UIButton(type: .system)
        _btn.tag = 2
        self.tableHeadView.addSubview(_btn)
        _btn.snp.makeConstraints({ make in
            make.left.equalTo(button1.snp.right).offset(20)
            make.centerY.equalTo(button1)
        })
        _btn.setTitle("测试按钮2", for: .normal)
        return _btn
    }()
    
    lazy var button3: UIButton = {
        let _btn = UIButton(type: .system)
        _btn.tag = 3
        self.tableHeadView.addSubview(_btn)
        _btn.snp.makeConstraints({ make in
            make.left.equalTo(button2.snp.right).offset(20)
            make.centerY.equalTo(button2)
        })
        _btn.setTitle("测试按钮3", for: .normal)
        return _btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupData()
//        _rxSwiftButtonProperty()
        _testRxIsSelectedProperty()
    }
    
    private func _testRxIsSelectedProperty() {
        // 按钮是否选中（isSelected）的绑定
        
        button1.isSelected = true
        let buttons = [button1, button2, button3]
        
        // 生成一个可观察序列数组 [Observable<UIButton>]
        let btnObservableArr = buttons.map({ (button) -> Observable<UIButton> in
            button.rx.tap.map { button }
        })
        
        // { button in button.rx.tap.map { button } }
        // 创建一个可观察序列，它可以发送最后一次点击的按钮（也就是我们需要选中的按钮）
        let selectedButton = Observable.from(btnObservableArr).merge()
        
        // 对于每一个按钮都对selectedButton进行订阅，根据它是否是当前选中的按钮绑定isSelected属性
        for button in buttons {
            selectedButton.map({ (current) -> Bool in
//                { $0 == button }
                print(info: "current.tag \(current.tag) : \(current.isSelected), current == button: \(current == button), button.tag -> \(button.tag)")
                // 根据当前点击的是哪个按钮判断选中哪个
                return current == button
            }).bind(to: button.rx.isSelected).disposed(by: disposeBag)
        }
        
        // 订阅可观察序列，点击按钮会回调
        for btnObs in btnObservableArr {
            btnObs.subscribe { event in
                print(info: "selectedButton.subscribe \(event)")
            }.disposed(by: disposeBag)
        }
    }

    private func _rxSwiftButtonProperty() {
        // 事件绑定
        /// 这么写不会回调返回上一级界面还会崩溃，  只少了个onNext参数名
//        button1.rx.tap.subscribe { [weak self] in self!.showMessage("点击按钮1") }.disposed(by: disposeBag)
        button1.rx.tap.subscribe(onNext: { [weak self] in self!.showMessage("点击按钮1") }).disposed(by: disposeBag)
        // 或者这样写
//        button1.rx.tap.bind {  [weak self] in
//            self!.showMessage("点击按钮1")
//        }.disposed(by: disposeBag)
        
        // 标题绑定  (属性标题:rx.attributedTitle)
        Observable<Int>.interval(1, scheduler: MainScheduler.instance)
            .map { "计数 -> \($0)" }
            .bind(to: button1.rx.title(for: .normal))
            .disposed(by: disposeBag)
        
        // 图片绑定
        Observable<Int>.interval(1, scheduler: MainScheduler.instance)
            .map { return UIImage(named: $0%2 == 0 ? "btn_last_play" : "btn_next_play") }
            .bind(to: button1.rx.image(for: .normal))
            .disposed(by: disposeBag)
        
        // 按钮是否可用（rx.isEnabled）的绑定
        // rx.backgroundImage的绑定
    }
    
    //显示消息提示框
    private func showMessage(_ text: String) {
        let alertController = UIAlertController(title: text, message: nil, preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    private func setupData() {
        let titles = [
            "init按钮类型 UIButton(type: )",
            "UIButton状态",
            "UIButton常用属性",
            "UIButton添加事件",
            "adjustsImageWhenDisabled",
            "adjustsImageWhenHighlighted",
            "showsTouchWhenHighlighted",
            "contentEdgeInsets",
            "imageEdgeInsets",
            "titleEdgeInsets"]
        
        let descArr = [
            """
            UIButtonType.system：前面不带图标，默认文字颜色为蓝色，有触摸时的高亮效果
            UIButtonType.custom：定制按钮，前面不带图标，默认文字颜色为白色，无触摸时的高亮效果
            UIButtonType.contactAdd：前面带“+”图标按钮，默认文字颜色为蓝色，有触摸时的高亮效果
            UIButtonType.detailDisclosure：前面带“!”图标按钮，默认文字颜色为蓝色，有触摸时的高亮效果
            UIButtonType.infoDark：为感叹号“!”圆形按钮
            UIButtonType.infoLight：为感叹号“!”圆形按钮
            自ios7起，infoDark、infoLight、detailDisclosure效果都是一样的
            """,
            """
            UIControlStateNormal          // 正常状态
            UIControlStateHighlighted     // 高亮状态
            UIControlStateDisabled        // 禁用状态
            UIControlStateSelected        // 选中状态
            UIControlStateFocused         // 聚焦状态
            UIControlStateApplication     // 当用做应用标志时
            UIControlStateReserved        // 保留状态
            """,
            """
            不能使用label对象设置文字的相关属性,必须使用以下方法设置对应状态的值:
            //设置对应状态的标题内容default is nil. title is assumed to be single line
            - (void)setTitle:(NSString *)title forState:(UIControlState)state;
            //设置对应状态的标题颜色
            - (void)setTitleColor:(UIColor *)color forState:(UIControlState)state;
            //设置对应状态的标题阴影颜色
            - (void)setTitleShadowColor:(UIColor *)color forState:(UIControlState)state;
            //设置对应状态的按钮的图片
            - (void)setImage:(UIImage *)image forState:(UIControlState)state;
            //设置对应状态的按钮背景图片
            - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;
            """,
            """
            - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
            这些事件都是基于触摸、基于值、基于编辑。有如下事件会触发。
            在点击按钮是按钮是凹下去，然后弹起才触发起事件，按钮的状态有：
            1.UIControlEventTouchDown       // 按下
            2.UIControlEventTouchDownRepeat // 多次按下
            3.UIControlEventTouchUpInside   // 在按钮及其一定外围内松开
            4.UIControlEventTouchUpOutside  // 按钮外面松开
            """,
            "当按钮禁用的情况下，图像的颜色会被画深一点，默认为YES",
            "当按钮高亮的情况下，图像的颜色会被画深一点，默认为YES",
            "button.showsTouchWhenHighlighted = YES;点击时的闪光效果会被前景图片遮住中间部分",
            "设置按钮的内部内容（包含按钮图片和标题）离按钮边缘上下左右的距离",
            "调整图片离按钮边缘上下左右的距离",
            "调整标题离按钮边缘上下左右的距离"]
        
        addTitles(titles, footDescs: descArr)
    }
    
}
